package com.ruoyi.edu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.edu.domain.EduCourse;
import com.ruoyi.edu.domain.EduVideo;
import com.ruoyi.edu.domain.chapter.ChapterVo;
import com.ruoyi.edu.domain.chapter.VideoVo;
import com.ruoyi.edu.domain.vo.CourseChildrenVo;
import com.ruoyi.edu.domain.vo.EduCourseVo;
import com.ruoyi.edu.mapper.EduCourseMapper;
import com.ruoyi.edu.mapper.EduVideoMapper;
import com.ruoyi.edu.service.IEduVideoService;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.edu.domain.bo.EduChapterBo;
import com.ruoyi.edu.domain.vo.EduChapterVo;
import com.ruoyi.edu.domain.EduChapter;
import com.ruoyi.edu.mapper.EduChapterMapper;
import com.ruoyi.edu.service.IEduChapterService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程章节管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-08-16
 */
@RequiredArgsConstructor
@Service
public class EduChapterServiceImpl implements IEduChapterService {

    private final EduChapterMapper baseMapper;
    @Autowired
    private IEduVideoService eduVideoService;
    private final EduCourseMapper eduCourseMapper;
    private final EduVideoMapper eduVideoMapper;
    /**
     * 查询课程章节管理
     */
    @Override
    public EduChapterVo queryById(String id){
        EduChapterVo eduChapterVo = baseMapper.selectVoById(id);
        EduCourseVo eduCourseVo = eduCourseMapper.selectVoById(eduChapterVo.getCourseId());
        eduChapterVo.setTitleC(eduCourseVo.getTitle());
        return eduChapterVo;
    }


    /**
     * 查询课程章节管理列表
     */
    @Override
    public TableDataInfo<EduChapterVo> queryPageList(EduChapterBo bo, PageQuery pageQuery) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(bo.getCourseId())){
            wrapper.eq("course_id",bo.getCourseId());
        }
        if (StringUtils.isNotEmpty(bo.getTitle())){
            wrapper.like("title",bo.getTitle());
        }
        wrapper.orderByAsc("sort");

        Page<EduChapterVo> result = baseMapper.selectVoPage(pageQuery.build(), wrapper);
        List<EduChapterVo> records = result.getRecords();

        List<EduChapterVo> collect = records.stream().map(item -> {
            QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("chapter_id",item.getId());
            queryWrapper.orderByAsc("sort");
            List<EduVideo> list = eduVideoService.list(queryWrapper);
            item.setChildren(list);

            return item;
        }).collect(Collectors.toList());
        result.setRecords(collect);
        return TableDataInfo.build(result);
    }


    /**
     * 查询课程章节管理树形列o
     */
//    @Override
//    public TableDataInfo<CourseChildrenVo> queryPageListVo(EduChapterBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<EduChapter> lqw = buildQueryWrapper(bo);
//        Page<CourseChildrenVo> result = baseMapper.selectPage(pageQuery.build(), lqw);
//        List<CourseChildrenVo> records = result.getRecords();
//        ArrayList<EduChapterVo> list = new ArrayList<>();
//        for (EduChapterVo eduChapterVo:records){
//            EduCourseVo eduCourseVo = eduCourseMapper.selectVoById(eduChapterVo.getCourseId());
//            eduChapterVo.setTitleC(eduCourseVo.getTitle());
//            list.add(eduChapterVo);
//        }
//        return TableDataInfo.build(list,result.getTotal());
//    }

    /**
     * 查询课程章节管理列表
     */
    @Override
    public List<EduChapterVo> queryList(EduChapterBo bo) {
        LambdaQueryWrapper<EduChapter> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EduChapter> buildQueryWrapper(EduChapterBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<EduChapter> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCourseId()), EduChapter::getCourseId, bo.getCourseId());
//        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), EduChapter::getTitle, bo.getTitle());
        lqw.like(StringUtils.isNotBlank(bo.getTitle()),EduChapter::getTitle,bo.getTitle());
        return lqw;
    }

    /**
     * 新增课程章节管理
     */
    @Override
    public Boolean insertByBo(EduChapterBo bo) {
        EduChapter add = BeanUtil.toBean(bo, EduChapter.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改课程章节管理
     */
    @Override
    public Boolean updateByBo(EduChapterBo bo) {
        EduChapter update = BeanUtil.toBean(bo, EduChapter.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EduChapter entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除课程章节管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {


        //1 根据课程id查询课程里面的章节
        QueryWrapper<EduChapter> wrapperChapter = new QueryWrapper<>();
        wrapperChapter.eq("course_id",courseId);
        List<EduChapter> eduChapterList = baseMapper.selectList(wrapperChapter);

        //2 根据课程id查询课程里面的小节
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
//        List<EduVideo> eduVideoVoList = eduVideoMapper.selectVoList(wrapperVideo);
//        List<EduVideo> eduVideoList = eduVideoMapper.selectList(wrapperVideo);
        List<EduVideo> eduVideoList = eduVideoService.list(wrapperVideo);
        //创建list集合，用于最终封装的集合
        List<ChapterVo> finallList = new ArrayList<>();

        //3 遍历查询章节list集合进行封装
        for (int i = 0; i < eduChapterList.size(); i++) {
            //得到每个章节
            EduChapter eduChapter = eduChapterList.get(i);
            //将edChapter对象复制到ChapterVo里面
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            //把chapterVo放到最终的list集合中
            finallList.add(chapterVo);

            //创建集合，用于封装章节中的小节
            List<VideoVo> videoList = new ArrayList<>();

            //4 遍历查询小节list集合进行封装
            for (int m = 0; m < eduVideoList.size(); m++) {
                //得到每个小节
                EduVideo eduVideo = eduVideoList.get(m);
                //判断：小节里面chapterid和章节里面的id是否一样
                if (eduVideo.getChapterId().equals(eduChapter.getId())) {
                    //进行封装
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo,videoVo);
                    //放在小节的集合中
                    videoList.add(videoVo);
                }
            }
            //把封装之后的小节list集合，放到章节对象里面
            chapterVo.setChildren(videoList);
        }
        return finallList;
    }




//如果有小节则章节无法删除
//    @Override
//    public boolean deleteChapter(String chapterId) {
//        //根据chapterid章节id查询小节表，如果查询到数据，不进行删除
//        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
//        wrapper.eq("chapter_id",chapterId);
//        int count = eduVideoService.count(wrapper);
//
//        if (count > 0) {//查询出小节，不进行删除
//            throw new GuliException(20001,"不能删除");
//        }else{//没有查询数据，进行删除
//            //删除章节
//            int result = baseMapper.deleteById(chapterId);
//            //成功 1>0  0>0
//            return result>0;
//        }
//
//    }

}
